import 'package:bloc/bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:myapp/models/comment.dart';

import '../../repositories/repositories.dart';

part 'comment_event.dart';
part 'comment_state.dart';

class CommentBloc extends Bloc<CommentEvent, CommentState> {
  final ArticleRepository articleRepository;
  CommentBloc({required this.articleRepository}) : super(CommentInitial()) {
    on<LoadCommentsEvent>((event, emit) async {
      emit(CommentsLoading());
      try {
        var comments= await articleRepository.getComments(event.slug);
        emit(CommentsLoaded(comments: comments));
      } catch (e) {
        emit(CommentError(error: e));
      }
    });

    on<CreateCommentEvent>((event, emit) async {
       await articleRepository.createComment(event.slug, event.comment);
    });
    on<DeleteCommentEvent>((event, emit) async {
       await articleRepository.deleteComment(event.slug, event.id);
    });
  }
}
